package com.misty.reflect;

import org.junit.Test;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class MethodTest {
    /**
     * 测试公有方法
     */
    @Test
    public void demo1() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        Class class1 = Class.forName("com.imist.Person");
        Person person = (Person) class1.newInstance();
        //得到公有方法，没有参数，可变参数类型可以不填或者null
        Method method = class1.getMethod("say");
        method.invoke(person);
    }
    /**
     * 测试私有方法
     */
    @Test
    public void demo2() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        Class class1 = Class.forName("com.imist.Person");
        Person person = (Person) class1.newInstance();
        //得到公有方法，没有参数，可变参数类型可以不填或者null
        Method method = class1.getDeclaredMethod("run");
        //设置私有方法的访问权限
        method.setAccessible(true);
        method.invoke(person);
    }
    /**
     * 测试私有方法，带参数
     */
    @Test
    public void demo3() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        Class class1 = Class.forName("com.imist.Person");
        Person person = (Person) class1.newInstance();
        //得到公有方法，指定方法名和参数类型，可变参数类型可以不填或者null
        Method method = class1.getDeclaredMethod("sayHello", String.class);
        //设置私有方法的访问权限
        method.setAccessible(true);
        //调用方法
        Object obj = method.invoke(person,"测试参数");
        System.out.println("返回值："+obj);
    }
    /**
     * 测试私有静态方法，带参数
     */
    @Test
    public void demo4() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        Class class1 = Class.forName("com.imist.Person");
        Person person = (Person) class1.newInstance();
        //得到公有方法，指定方法名和参数类型，可变参数类型可以不填或者null
        Method method = class1.getDeclaredMethod("utils", String.class);
        //设置私有方法的访问权限
        method.setAccessible(true);
        //调用静态方法，只需要将实例对象设置为null即可
        Object obj = method.invoke(null,"测试参数");
        System.out.println("返回值："+obj);
    }


}
